package cn.lijigou.shopping;

import java.util.concurrent.ExecutorService;

import org.json.JSONException;
import org.json.JSONObject;

import com.umeng.api.exp.UMSNSException;
import com.umeng.api.sns.UMSnsService;
import com.umeng.api.sns.UMSnsService.SHARE_TO;

import cn.lijigou.shopping.domain.MResult;
import cn.lijigou.shopping.domain.User;
import cn.lijigou.shopping.service.MSystem;
import cn.lijigou.shopping.service.ServerService;
import cn.lijigou.shopping.util.GetSingleThreadPool;
import cn.lijigou.shopping.util.StringTool;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author 董永健 E-mail:dong_yong_jian@163.com
 * @version CreatTime：2011-3-30 上午11:27:24
 * 类说明
 */
public class LoginActivity extends MActivity implements OnClickListener{
	private TextView back= null;
	private LinearLayout titleLeftView= null;
	private TextView title_right= null;
	private Button login_btn= null;
	private TextView error_content= null;
	private TextView title_center= null;
	
	private EditText edit_email;
	private EditText edit_password;
	private LinearLayout bottom_linear;
	private LinearLayout error_linear;
	
	private String input_string="";
	private String password="";
	private String session = "";
	private String uid = "";
	private User user = null;
	private String result = "";
	
	private String sessionKey;
	private String nickname;
	private String id;
	
	private LinearLayout login_qq = null;
	private LinearLayout login_sina = null;
	private LinearLayout login_renren = null;
	private String	secret = "";
	private String	key = "";
	private ProgressDialog mProgress;
	private ExecutorService executorService = GetSingleThreadPool.getInstance();
	
	public Handler resultHander = new Handler(){
		
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			
			if(msg.what==1){
				resultAlert(result);
			}
		}
	};
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.setContentView(R.layout.login);
		overridePendingTransition(R.anim.push_in,R.anim.push_out);

		setViews();
		setDatas();
		setOnClickListeners();
	}
	
	
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}
	
	private void  setViews(){

		back = (TextView) this.findViewById(R.id.title_btn_left);
		titleLeftView = (LinearLayout) this.findViewById(R.id.titleLeftView);
		back.setBackgroundResource(R.drawable.title_back_normal);

		title_right = (TextView) this.findViewById(R.id.title_btn_right);
		title_right.setVisibility(View.GONE);
		title_center = (TextView) this.findViewById(R.id.text_center);
		if (MSystem.isLogin(this, 0)) {
			if (MSystem.isLoginDummy(this)) {
				title_center.setText(R.string.login);
			} else {
				title_center.setText(R.string.switch_accounts);
			}

		}else{
			title_center.setText(R.string.login);
		}
		findViewById(R.id.titleRightView).setVisibility(View.GONE);
		
		edit_email = (EditText) findViewById(R.id.edit_email);
		edit_password = (EditText) findViewById(R.id.edit_password);
		bottom_linear=(LinearLayout) findViewById(R.id.bottom_linear);
		error_linear=(LinearLayout) findViewById(R.id.error_linear);
		login_btn =(Button) findViewById(R.id.login_btn);
		error_content =(TextView) findViewById(R.id.error_content);
		login_qq = (LinearLayout) this.findViewById(R.id.login_qq);
		login_sina = (LinearLayout) this.findViewById(R.id.login_sina);
		login_renren = (LinearLayout) this.findViewById(R.id.login_renren);
		
	}
	private void  setOnClickListeners(){
		titleLeftView.setOnClickListener(this);
		login_btn.setOnClickListener(this);
		login_qq.setOnClickListener(this);
		login_sina.setOnClickListener(this);
		login_renren.setOnClickListener(this);
	}
	private void  setDatas(){
		
	}

	public void onClick(View v) {
		MSystem.pv += 1;
		switch (v.getId()) {
		case R.id.titleLeftView:
			this.finish();
			break;
		case R.id.login_btn:
			input_string = edit_email.getText().toString();
			password = edit_password.getText().toString();
			if (StringTool.isNull(input_string)) {
				showError(1);
			} else if (!StringTool.isEmail(input_string) && !StringTool.isMobileNO(input_string)) {
				showError(8);
			} else if (StringTool.isNull(password)) {
				showError(3);
			} else {
				user = new User(sessionKey, nickname, id);
				executorService.execute(new Thread() {
					public void run() {
						showProgress();
						MResult mResult = MSystem.Login(user, input_string, password);
						result = mResult.getErrorCode();
						resultHander.sendEmptyMessage(1);
						hideProgress();
					}
				});

			}
			break;
		case R.id.login_qq:
			UMSnsService.OauthCallbackListener listener_qq = new UMSnsService.OauthCallbackListener() {

				
				public void onError(UMSNSException arg0, SHARE_TO arg1) {
					Toast.makeText(LoginActivity.this, "认证失败，请稍后再试", 1).show();
					arg0.printStackTrace();
				}

				
				public void onComplete(Bundle arg0, SHARE_TO arg1) {
					JSONObject info_qq = UMSnsService.getAccessToken(LoginActivity.this, SHARE_TO.TENC);

					try {
						String uid = info_qq.getString("uid");
						secret = info_qq.getString("secret");
						key = info_qq.getString("key");
						user = new User(sessionKey, nickname, id);
						executorService.execute(new Thread() {
							public void run() {
								showProgress();
								MResult mResult = MSystem.login_register_weibo(user, key, secret, "qq");
								result = mResult.getErrorCode();
								resultHander.sendEmptyMessage(1);
								hideProgress();
							}
						});
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}
			};
			UMSnsService.oauthTenc(LoginActivity.this, listener_qq);
			break;
		case R.id.login_sina:
			UMSnsService.OauthCallbackListener listener_sina = new UMSnsService.OauthCallbackListener() {

				
				public void onError(UMSNSException arg0, SHARE_TO arg1) {
					Toast.makeText(LoginActivity.this, "认证失败，请稍后再试", 1).show();
					arg0.printStackTrace();
				}

				
				public void onComplete(Bundle arg0, SHARE_TO arg1) {
					JSONObject info_sina = UMSnsService.getAccessToken(LoginActivity.this, SHARE_TO.SINA);
					try {
						String uid = info_sina.getString("uid");
						secret = info_sina.getString("secret");
						key = info_sina.getString("key");
						user = new User(sessionKey, nickname, id);
						executorService.execute(new Thread() {
							public void run() {
								showProgress();
								MResult mResult = MSystem.login_register_weibo(user, key, secret, "sina");
								result = mResult.getErrorCode();
								resultHander.sendEmptyMessage(1);
								hideProgress();
							}
						});
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			};
			UMSnsService.oauthSina(LoginActivity.this, listener_sina);

			break;
		case R.id.login_renren:
			UMSnsService.OauthCallbackListener listener_renren = new UMSnsService.OauthCallbackListener() {

				
				public void onError(UMSNSException arg0, SHARE_TO arg1) {
					Toast.makeText(LoginActivity.this, "认证失败，请稍后再试", 1).show();
					arg0.printStackTrace();
				}

				
				public void onComplete(Bundle arg0, SHARE_TO arg1) {
					JSONObject info_renren = UMSnsService.getAccessToken(LoginActivity.this, SHARE_TO.RENR);
					try {
						String uid = info_renren.getString("uid");
						secret = info_renren.getString("secret");
						key = info_renren.getString("key");
						user = new User(sessionKey, nickname, id);
						executorService.execute(new Thread() {
							public void run() {
								showProgress();
								MResult mResult = MSystem.login_register_weibo(user, key, secret, "renren");
								result = mResult.getErrorCode();
								resultHander.sendEmptyMessage(1);
								hideProgress();
							}
						});
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			};
			UMSnsService.oauthRenr(LoginActivity.this, listener_renren);
			break;

		}
	}

	public void resultAlert(String result) {
		LayoutInflater inflater = getLayoutInflater();
		View layout = inflater.inflate(R.layout.toast_error,(ViewGroup) findViewById(R.id.llToast));
		ImageView image = (ImageView) layout.findViewById(R.id.tvImageToast);
		image.setImageResource(R.drawable.icon);
		TextView title = (TextView) layout.findViewById(R.id.tvTitleToast);
		TextView text = (TextView) layout.findViewById(R.id.tvTextToast);
		if ("".equals(result)) {
			title.setText(R.string.login_successful);
			text.setText(R.string.thanks_for_using);
			SharedPreferences sp = LoginActivity.this.getSharedPreferences("user", Context.MODE_PRIVATE);
			Editor edit = sp.edit();
			edit.clear().commit();
			edit.putString("uid",user.getId());
			edit.putString("session",user.getSessionKey());
			edit.putString("nickname",user.getNickname());
			edit.putString("isTmp",user.getIsTmp());
			edit.commit();
			Toast toast = new Toast(this);
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.setDuration(Toast.LENGTH_LONG);
			toast.setView(layout);
			toast.show();
			//保证切换账号后 跳转到我的订单，刷新订单
			OrdersActivity.pages[0] = 1;
			OrdersActivity.pages[1] = 1;
			OrdersActivity.radioButtonId =0;
			OrdersActivity.mPayedOrders.clear();
			OrdersActivity.mUnPayOrders.clear();
			OrdersActivity.hasNextPages[0]=true;
			OrdersActivity.hasNextPages[1]=true;
			this.finish();
		}else if ("#1004".equals(result)) {
			error_linear.setVisibility(View.VISIBLE);
			error_content.setText(R.string.Password_is_incorrect_please_re_enter);
		} else if ("#2001".equals(result)) {
			error_linear.setVisibility(View.VISIBLE);
			error_content.setText(R.string.phone_number_does_not_exist);
		} else if ("#2002".equals(result)) {
			error_linear.setVisibility(View.VISIBLE);
			error_content.setText(R.string.mailbox_does_not_exist);
		}else if ("#2003".equals(result)) {
			error_linear.setVisibility(View.VISIBLE);
			error_content.setText(R.string.e_mail_or_phone_number_is_wrong);
		}else if ("#1001".equals(result)) {
			error_linear.setVisibility(View.VISIBLE);
			error_content.setText(R.string.user_name_or_password_can_not_be_empty);
		}
		
	}
	
	public void showError(int id){
		switch (id) {
		case 1:
			error_content.setText(R.string.account_can_not_be_empty);
			break;
		case 2:
			error_content.setText(R.string.e_mail_account_does_not_meet_the_format);
			break;
		case 3:
			error_content.setText(R.string.password_can_not_be_empty);
			break;
		case 4:
			error_content.setText(R.string.user_name_or_password_can_not_be_empty);
			break;
		case 5:
			error_content.setText(R.string.phone_or_email_does_not_exist);
			break;
		case 6:
			error_content.setText(R.string.not_verified_by_phone);
			break;
		case 7:
			error_content.setText(R.string.not_verified_by_mail);
			break;
		case 8:
			error_content.setText(R.string.e_mail_or_phone_number_is_wrong);
			break;
		case 9:
			error_content.setText(R.string.the_password_is_incorrect);
			break;
		}
		error_linear.setVisibility(View.VISIBLE);
		
	}
	
	/**
	 * 显示等待框
	 * 
	 * @param title
	 * @param message
	 */
	protected void showProgress() {
		this.runOnUiThread(new Runnable() {
			

			public void run() {	
				mProgress = new ProgressDialog(LoginActivity.this);
				mProgress.requestWindowFeature(Window.FEATURE_NO_TITLE);
				mProgress.setMessage("正在登录，请稍后...");
				mProgress.show();
			}
		});
	}

	/**
	 * 取消等待框
	 */
	protected void hideProgress() {
		
		this.runOnUiThread(new Runnable() {
			public void run() {
				if (mProgress != null) {
					mProgress.dismiss();
				}
			}
		});
	}
	
}
